package com.xujl.task.follow;

import android.util.SparseArray;

import com.xujl.task.TaskUtils;

import java.util.LinkedHashMap;

/**
 * 流程控制器
 * 用于把多个异步任务结果放在一个队列中
 * 队列任务依次执行，阻塞式队列
 * RxFollow任务是运行在主线程中的，请勿在任务中直接进行耗时
 * 操作，否则会anr
 */
public class RxFollow {
    /**
     * 流程任务步骤数据结果
     */
    private SparseArray<Object> mStepData = new SparseArray<>();

    private LinkedHashMap<Integer, IFollowStep> mFollowSteps = new LinkedHashMap<>();
    /**
     * 流程执行器
     */
    private IActuator mActuator;

    private RxFollow () {
        setActuator(new QueueActuator());
    }

    public static RxFollow create () {
        return new RxFollow();
    }

    public RxFollow setActuator (IActuator actuator) {
        mActuator = actuator;
        mActuator.init(this);
        return this;
    }

    public RxFollow addFollow (IFollowStep followStep) {
        final int code = TaskUtils.getRandomForIntegerBounded(0, Integer.MAX_VALUE);
        if (mFollowSteps.containsKey(code)) {
            return addFollow(followStep);
        }
        return addFollow(code, followStep);
    }

    public RxFollow addFollow (int code, IFollowStep followStep) {
        mFollowSteps.put(code, followStep);
        return this;
    }

    public <T> T getStepResult (int code) {
        return (T) mStepData.get(code);
    }

    public void startFollow () {
        mActuator.start();
    }

    public SparseArray<Object> getStepData () {
        return mStepData;
    }

    public void setStepData (SparseArray<Object> stepData) {
        mStepData = stepData;
    }

    public LinkedHashMap<Integer, IFollowStep> getFollowSteps () {
        return mFollowSteps;
    }

    public void setFollowSteps (LinkedHashMap<Integer, IFollowStep> followSteps) {
        mFollowSteps = followSteps;
    }
}
